<?php
/**
 * 公共函数库
 * @auther 小林 《1814992057@qq.com》
 * @datetime   2019/08/23
 */
use Symfony\Component\HttpFoundation\Response;
use OSS\OssClient;
use OSS\Core\OssException;
use  Mews\Captcha\Facades\Captcha;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
// require_once("../OpenSearch/Autoloader/Autoloader.php");
use OpenSearch\Client\OpenSearchClient;
use App\User;
use App\Permission;
use Mrgoon\AliSms\AliSms;


/*
 *  抛出异常
 * */
function ThrowApiExc($code,$msg=''){

    $data = [
        'status_code' =>$code,
        'message'     =>config('show_status.'.$code,$msg),
        'data'        =>""
    ];

    return response()->json($data, 200);

} 
    
function returnImgJson($base64){
    $host = "https://ocrapi-advanced.taobao.com";
    $path = "/ocrservice/advanced";
    $method = "POST";
    $appcode = "97d34eeaa6da405cb72838423e8fc0b7";
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    //根据API的要求，定义相对应的Content-Type
    array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
    $querys = "";
    $bodys = json_encode([
        'url'=>$base64
    ]);
    $url = $host . $path;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    if (1 == strpos("$".$host, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);

    return curl_exec($curl);
    
}


function returnImgJson2($base64){

    $host = "https://ocrapi-advanced.taobao.com";
    $path = "/ocrservice/advanced";
    $method = "POST";
    $appcode='8233784bd5234f0285fe5f8ebe70827f';
    $headers = array();
    array_push($headers, "Authorization:APPCODE " . $appcode);
    //根据API的要求，定义相对应的Content-Type
    array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
    $querys = "";
    $bodys = "{\"url\":\"".$base64."\"}";


//    return $bodys;
    $url = $host . $path;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);

    if (1 == strpos("$".$host, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
    return curl_exec($curl);

}

    /*
     * Oss存储
     * */

    function Oss($filePath,$object){
        $accessKeyId = "LTAIh0CUylpfHN2m";
        $accessKeySecret = "NGVVKlDcvISGcysImkNJVwX2eDNiex";
// Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "http://oss-cn-beijing.aliyuncs.com";
// 存储空间名称
        $bucket= "jializhishi";
// 文件名称
//        $content = "$base64";
//        $filePath = "文件地址";

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
//            $res = $ossClient->putObject($bucket, $object, $filePath);
            $res = $ossClient->uploadFile($bucket, $object, $filePath);
            return $res;
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

    
    function Oss2($filePath,$object){
        $accessKeyId = "LTAIh0CUylpfHN2m";
        $accessKeySecret = "NGVVKlDcvISGcysImkNJVwX2eDNiex";
// Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = "http://oss-cn-beijing.aliyuncs.com";
// 存储空间名称
        $bucket= "jializhishi";
// 文件名称
//        $content = "$base64";
//        $filePath = "文件地址";

        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            // $res = $ossClient->uploadContent($bucket, $object, $filePath);
            // $res = $ossClient->uploadFile($bucket, $object, $filePath);
            return $res;
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }



    function create($keys){
        foreach ($keys as $k=>$v){
            $data[$v]=config('pro_array.'.$v);
        }
        return $data;
    }


    function code_img(){

        return ;

    }


//    /**
//     * 返回reids实例
//     * @param $db int   要选择的数据库
//     * @return Redis  Object  一个redis实例
//     */
//    function getRedis($key = 0)
//    {
//        $redis = Redis::get($key.':1');
//
//        return $redis;
//
//    }

    function getToken($request){

        $header = $request->server->get('HTTP_AUTHORIZATION');

        $prefix = 'bearer';
        if ($header && preg_match('/'.$prefix.'\s*(\S+)\b/i', $header, $matches)) {
            return $matches[1];
        }
        return false;
    }



    function checkNatInt($str) {
        $map = array(
            '一' => '1','二' => '2','三' => '3','四' => '4','五' => '5','六' => '6','七' => '7','八' => '8','九' => '9',
            '壹' => '1','贰' => '2','叁' => '3','肆' => '4','伍' => '5','陆' => '6','柒' => '7','捌' => '8','玖' => '9',
            '零' => '0','两' => '2',
            '仟' => '千','佰' => '百','拾' => '十',
            '万万' => '亿',
        );

        $str = str_replace(array_keys($map), array_values($map), $str);
//        $str = checkString($str, '/([\d亿万千百十]+)/u');

        $func_c2i = function ($str, $plus = false) use(&$func_c2i) {
            if(false === $plus) {
                $plus = array('亿' => 100000000,'万' => 10000,'千' => 1000,'百' => 100,'十' => 10,);
            }

            $i = 0;
            if($plus)
                foreach($plus as $k => $v) {
                    $i++;
                    if(strpos($str, $k) !== false) {
                        $ex = explode($k, $str, 2);
                        $new_plus = array_slice($plus, $i, null, true);
                        $l = $func_c2i($ex[0], $new_plus);
                        $r = $func_c2i($ex[1], $new_plus);
                        if($l == 0) $l = 1;
                        return $l * $v + $r;
                    }
                }

            return (int)$str;
        };
    return $func_c2i($str);
    }

function getip() {
    static $ip = '';
    $ip = $_SERVER['REMOTE_ADDR'];
    if(isset($_SERVER['HTTP_CDN_SRxC_IP'])) {
        $ip = $_SERVER['HTTP_CDN_SRC_IP'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] AS $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    }
    return $ip;
}

function quid($uid){
    $qu = DB::table("Q_q_p_users")->where([
        ['qid',5],
        ['userId',$uid]
    ])->first();
    if($qu){
        return $qu['id'];
    }else{
        return DB::table("Q_q_p_users")->insertGetId([
            "qid"=>5,
            "userId"=>$uid,
            "description"=>"胖虎",
            "createdTime"=>date("Y-m-d H:i:s",time()),
            "updateTime"=>date("Y-m-d H:i:s",time())
        ]);
    }
}

function object_array($array)
{
    if(is_object($array))
    {
        $array = (array)$array;
    }
    if(is_array($array))
    {
        foreach($array as $key=>$value)
        {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

function _checkAssocArray($arr)
{
    $index = 0;
    foreach (array_keys($arr) as $key) {
        if ($index++ != $key) return false;
    }
}

function OSclient(){
    //替换对应的access key id
    $accessKeyId = 'LTAI4FdJSDEbmddRRa76pxHS';
//替换对应的access secret
    $secret = 'UkRkAGINzR6vEdAsP1ixhd1KJrq7RK';
//替换为对应区域api访问地址，可参考应用控制台,基本信息中api地址
    $endPoint = 'http://opensearch-cn-beijing.aliyuncs.com';
//替换为应用名
    $appName = 'jiali_smart';
//替换为下拉提示名称
    $suggestName = 'jiali_smart';
//开启调试模式
    $options = array('debug' => true);
//创建OpenSearchClient客户端对象
    $client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);

    return $client;

}

function OSclient2(){
    //替换对应的access key id
    $accessKeyId = 'LTAI4FdJSDEbmddRRa76pxHS';
//替换对应的access secret
    $secret = 'UkRkAGINzR6vEdAsP1ixhd1KJrq7RK';
//替换为对应区域api访问地址，可参考应用控制台,基本信息中api地址
    $endPoint = 'http://opensearch-cn-beijing.aliyuncs.com';
//替换为应用名
    $appName = 'jiali_smart_news';
//替换为下拉提示名称
    $suggestName = 'jiali_smart_news';
//开启调试模式
    $options = array('debug' => true);
//创建OpenSearchClient客户端对象
    $client = new OpenSearchClient($accessKeyId, $secret, $endPoint, $options);




    return $client;

}

function removal($oldData,$newData){

        foreach ($oldData as $k=>$v){

            foreach ($newData as $kk=>&$vv){

                if($v['id']==$vv['fields']['id']){
                    unset($newData[$k]);
                }

            }

        }

        foreach ($newData as $k=>$v){
            $oldData[]=$v['fields'];
        }

        return $oldData;

}


/**
 * 宣判权限
 */
function if_authority($uid,$permissions){
    $user = User::find($uid);
    if($user->can($permissions)){
        return true;
    }else{
        return false;
    }
}


/**
 * 发送短信验证码
 */

function aliyun_sms($account,$msg,$params){

    if(Redis::get("phone_cd:".$account)) return ThrowApiExc('32040');

    $config = [
        'access_key' => 'LTAI4G9eRSSGG64VJwED1aQa',
        'access_secret' => '172GfY634cyp0Ww1xNHMWdUpbGx8Ov',
        'sign_name' => '家理律所',
    ];
    $aliSms = new AliSms();
    $response = $aliSms->sendSms($account, $msg,["code"=>$params], $config);
    if($response->Message!="OK"){
        return ThrowApiExc("32039");
    }
    $ttl = 10*60;  //过期时间 N 分钟
    Redis::setex("phone_time:".$account ,$ttl,$params);
    Redis::setex("phone_cd:".$account ,60,$params);

    return 1;
}

function aliyun_sms2($account,$msg,$params){

    // if(Redis::get("phone_cd:".$account)) return ThrowApiExc('32040');

    $config = [
        'access_key' => 'LTAI4G9eRSSGG64VJwED1aQa',
        'access_secret' => '172GfY634cyp0Ww1xNHMWdUpbGx8Ov',
        'sign_name' => '家理律所',
    ];
    $aliSms = new AliSms();
    $response = $aliSms->sendSms($account, $msg,["code"=>$params], $config);
    if($response->Message!="OK"){
        return ThrowApiExc("32039");
    }
    $ttl = 10*60;  //过期时间 N 分钟
    Redis::setex("phone_time:".$account ,$ttl,$params);
    Redis::setex("phone_cd:".$account ,60,$params);
    var_dump($response);
    return;
}


function aliyun_huizhi($account,$msg,$params){

    // if(Redis::get("phone_cd:".$account)) return ThrowApiExc('32040');

    $config = [
        'access_key' => 'LTAI4G9eRSSGG64VJwED1aQa',
        'access_secret' => '172GfY634cyp0Ww1xNHMWdUpbGx8Ov',
        'sign_name' => '家理律所',
    ];
    $aliSms = new AliSms();
    $response = $aliSms->smsUp();
    var_dump($response);
    return;
}


//合并数组销毁重复的值
function second_array_unique_bykey($arr, $key){
    $tmp_arr = array();
    foreach($arr as $k => $v)
    {
        if(in_array($v[$key], $tmp_arr))   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
        {
            unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
        }
        else {
            $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
        }
    }
   //ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
    return $arr;
}


//action及子集
function select_news_action($id){

    $aids = [$id];
    $data = DB::table("action")->where("faId",$id)->get();
    foreach($data as $k=>$v){
        $aids=array_merge($aids,select_news_action($v['id']));
    }
    return $aids;
}



//日志
function add_user_log($type,$status,$content,$uid){
    //type 1操作文书 2操作文章
    //status 1新增 2修改 3删除 4查询 5复制 6搜索
    $res = DB::table("user_log")->insertGetId([
        "type"=>$type,
        "status"=>$status,
        "content"=>$content,
        "uid"=>$uid,
        "created_time"=>date("Y-m-d H:i:s",time()),
    ]);
}

function get_pdf($quid){

    $word_text=DB::table("Q_q_p_users")->where("id",$quid)->first()['content'];
        //添加页面

        $wordData=DB::table("Q_q_p_users as qqpu")
            ->leftJoin("Q_questionnaire as qq","qq.id","=","qqpu.qid")
            ->select("qq.title","qqpu.qid","qq.type")
            ->where("qqpu.id",$quid)
            ->first();

        $wordName=$wordData['title'];
        $newData = explode("\n",$word_text);
    $pdf = new \TCPDF();
        // 设置文档信息
        $pdf->SetCreator('懒人开发网');
        $pdf->SetAuthor('懒人开发网');
        $pdf->SetTitle('TCPDF示例');
        $pdf->SetSubject('TCPDF示例');
        $pdf->SetKeywords('TCPDF, PDF, PHP');

        // 设置页眉和页脚信息
        // $pdf->SetHeaderData('tcpdf_logo.jpg', 30, 'LanRenKaiFA.com', '学会偷懒，并懒出效率！', [0, 64, 255], [0, 64, 128]);
        // $pdf->setFooterData([0, 64, 0], [0, 64, 128]);

        // 设置页眉和页脚字体
        $pdf->setHeaderFont(['stsongstdlight', '', '10']);
        $pdf->setFooterFont(['helvetica', '', '8']);

        // 设置默认等宽字体
        $pdf->SetDefaultMonospacedFont('courier');

        // 设置间距
        $pdf->SetMargins(15, 15, 15);//页面间隔
        $pdf->SetHeaderMargin(5);//页眉top间隔
        $pdf->SetFooterMargin(10);//页脚bottom间隔

        // 设置分页
        $pdf->SetAutoPageBreak(true, 25);

        // set default font subsetting mode
        $pdf->setFontSubsetting(true);

        //设置字体 stsongstdlight支持中文
        $pdf->SetFont('stsongstdlight', '', 14);

        //第一页
        $pdf->AddPage();
        // $pdf->writeHTML('<p style="color: red">我是第二行内容</p>');
        // $pdf->writeHTML('<p>我是第三行内容</p>');
        // $pdf->writeHTML('<p><a href="http://www.lanrenkaifa.com/" title="">懒人开发网</a></p>');
        $pdf->writeHTML('<div style="text-align: center"><h1>'.$wordName.'</h1></div>');

        foreach ($newData as $k=>$v){
            
            // if(strpos($v,"<b>")!== false){
            //     $asr=explode("</b>",$v);
            //     $pdf->writeHTML('<p>'.htmlspecialchars(preg_replace("/[|]+/","",str_replace("<b>","",$asr[0]))),['bold' => true].'</p>');
            //     $pdf->writeHTML('<p>'.htmlspecialchars(preg_replace("/[|]+/","",$asr[1])).'</p>');
            //     $pdf->Ln(5);//换行符
            // }else{
            //     $pdf->writeHTML('<p>'.htmlspecialchars(preg_replace("/[|]+/","",str_replace("      ","  ",$v))).'</p>');
            // }
        $pdf->writeHTML('<p>'.str_replace("</b>","",str_replace("<b>","",str_replace(" ","&nbsp;",$v))).'</p>');
                // echo var_dump($v);
                // echo "</br>";
        }
        // die;
        //第二页
        // $pdf->AddPage();
        // $pdf->writeHTML('<h1>第二页内容</h1>');

        //输出PDF
        $pdf->Output('t.pdf', 'I');//I输出、D下载
}


//判断是否存在二级域名下
function is_TwoArray($data,$key,$value){
    foreach($data as $k=>$v){
        if($v[$key]==$value) return true;
    }
    return false;
}


function substr_cut($user_name){
    $strlen     = mb_strlen($user_name, 'utf-8');
    $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
    $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('某', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("某", $strlen - 3) . $lastStr;
}


function n2c($x) //单个数字变汉字
{
$arr_n = array("零","⼀","⼆","三","四","五","六","七","⼋","九","⼗");
return $arr_n[$x];
}


function get_aladin_token(){
    $accessKey_ID = "ALJIiYuZrKfhwI62";
    $accessKey_Secret = "i5HoG8Lfe6ajiXLN1FeyR2ltWhWOkT";
    
    $secretkey = urlencode(authcode($accessKey_Secret,'ENCODE',$accessKey_ID));
    
    $url = "https://office365.jialilaw.com/api/center/token/secretkey/".$secretkey;
    
    
    //返回json格式数据，如：{"token":"8ae4db8d3affe92175684f904eae5422","msg":""}
    //正确时，msg会为空，错误会显示相关错误信息
    //token默认有效2小时，现在未做限制

   
    $token_data = curl($url);
    
    $token = '';
    
    if($token_data != "")
    {
         $tmp_token = json_decode($token_data,"true");
         if($tmp_token['msg'] == '')
         {
            $token = $tmp_token['token'];
         }
    }else{
        $token=false;
    }
    return $token;
}


function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0){

    if($operation == 'DECODE') {
        $string = str_replace('[a]','+',$string);
        $string = str_replace('[b]','&',$string);
        $string = str_replace('[c]','/',$string);
    }
    $ckey_length = 4;
    $key = md5($key ? $key : 'livcmsencryption ');
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if($operation == 'DECODE') {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {

            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        $ustr = $keyc.str_replace('=', '', base64_encode($result));
        $ustr = str_replace('+','[a]',$ustr);
        $ustr = str_replace('&','[b]',$ustr);
        $ustr = str_replace('/','[c]',$ustr);
        return $ustr;
    }
}


function curl($url, $method = 'GET', $postFields = null, $header = null)
{

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36");

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

        curl_setopt($ch, CURLOPT_FAILONERROR, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        curl_setopt($ch, CURLOPT_TIMEOUT, 20);

        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {

                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        }


        switch ($method) {

                case 'POST':

                        curl_setopt($ch, CURLOPT_POST, true);

                        if (!empty($postFields) && is_array($postFields)) {

                                $postBodyString = "";

                                $postMultipart = false;

                                foreach ($postFields as $k => $v) {

                                        if ("@" != substr($v, 0, 1)) { //判断是不是文件上传

                                                $postBodyString .= "$k=" . urlencode($v) . "&";

                                        }

                                        else { //文件上传用multipart/form-data，否则用www-form-urlencoded

                                                $postMultipart = true;

                                        }

                                }

                                unset($k, $v);

                                if ($postMultipart) {

                                        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

                                }

                                else {

                                        curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));

                                }

                        }else if(!empty($postFields)){
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
                        }   

                        break;

                default:

                        if (!empty($postFields) && is_array($postFields))

                                $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($postFields);

                        break;

        }  
        curl_setopt($ch, CURLOPT_URL, $url);



        if (!empty($header) && is_array($header)) {

                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        }

        $reponse = curl_exec($ch);

        if (curl_errno($ch)) {

                throw new Exception(curl_error($ch),0);

        }

        curl_close($ch);

        return $reponse;

}




//提取字符串人名 转屏蔽为 李某1 李某2
function preg_name($str){
    $nameReg="/([\(,.，。:：、])(王|李|张|刘|陈|杨|黄|赵|吴|周|徐|孙|马|朱|胡|郭|何|高|林|罗|郑|梁|谢|宋|唐|许|韩|冯|邓|曹|彭|曾|肖|田|董|袁|潘|于|蒋|蔡|余|杜|叶|程|苏|魏|吕|丁|任|沈|姚|卢|姜|崔|钟|谭|陆|汪|范|金|石|廖|贾|夏|韦|傅|方|白|邹|孟|熊|秦|邱|江|尹|薛|闫|段|雷|侯|龙|史|黎|贺|顾|毛|郝|龚|邵|万|钱|覃|武|戴|孔|汤|庞|樊|兰|殷|施|陶|洪|翟|安|颜|倪|严|牛|温|芦|季|俞|章|鲁|葛|伍|申|尤|毕|聂|柴|焦|向|柳|邢|岳|齐|沿|梅|莫|庄|辛|管|祝|左|涂|谷|祁|时|舒|耿|牟|卜|路|詹|关|苗|凌|费|纪|靳|盛|童|欧|甄|项|曲|成|游|阳|裴|席|卫|查|屈|鲍|位|覃|霍|翁|隋|植|甘|景|薄|单|包|司|柏|宁|柯|阮|桂|闵|欧阳|解|强|丛|华|车|冉|房|边|辜|吉|饶|刁|瞿|戚|丘|古|米|池|滕|晋|苑|邬|臧|畅|宫|来|嵺|苟|全|褚|廉|简|娄|盖|符|奚|木|穆|党|燕|郎|邸|冀|谈|姬|屠|连|郜|晏|栾|郁|商|蒙|计|喻|揭|窦|迟|宇|敖|糜|鄢|冷|卓|花|艾|蓝|都|巩|稽|井|练|仲|乐|虞|卞|封|竺|冼|原|官|衣|楚|佟|栗|匡|宗|应|台|巫|鞠|僧|桑|荆|谌|银|扬|明|沙|薄|伏|岑|习|胥|保|和|蔺|水|云|昌|凤|酆|常|皮|康|元|平|萧|湛|禹|无|贝|茅|麻|危|骆|支|咎|经|裘|缪|干|宣|贲|杭|诸|钮|嵇|滑|荣|荀|羊|於|惠|家|芮|羿|储|汲|邴|松|富|乌|巴|弓|牧|隗|山|宓|蓬|郗|班|仰|秋|伊|仇|暴|钭|厉|戎|祖|束|幸|韶|蓟|印|宿|怀|蒲|鄂|索|咸|籍|赖|乔|阴|能|苍|双|闻|莘|贡|逢|扶|堵|宰|郦|雍|却|璩|濮|寿|通|扈|郏|浦|尚|农|别|阎|充|慕|茹|宦|鱼|容|易|慎|戈|庚|终|暨|居|衡|步|满|弘|国|文|寇|广|禄|阙|东|殴|殳|沃|利|蔚|越|夔|隆|师|厍|晃|勾|融|訾|阚|那|空|毋|乜|养|须|丰|巢|蒯|相|后|红|权逯|盖益|桓|公|万俟|司马|上官|夏侯|诸葛|闻人|东方|赫连|皇甫|尉迟|公羊|澹台|公冶|宗政|濮阳|淳于|单于|太叔|申屠|公孙|仲孙|轩辕|令狐|钟离|宇文|长孙|慕容|鲜于|闾丘|司徒|司空|亓官|司寇|仉|督|子车|颛孙|端木|巫马|公西|漆雕|乐正|壤驷|公良|拓跋|夹谷|宰父|谷粱|法|汝|钦|段干|百里|东郭|南门|呼延|归海|羊舌|微生|帅|缑|亢|况|郈|琴|梁丘|左丘|东门|西门|佘|佴|伯|赏|南宫|墨|哈|谯|笪|年|爱|仝|代)[\x{4e00}-\x{9fa5}]{1,2}([,.，。:：\(（)])/u";
    $delete_array=['满族',"汉族"];
    preg_match_all($nameReg,$str,$arr);
    
    if($arr){
        foreach($arr[0] as $k=>$v){
            $arr[0][$k]=str_replace($arr[3][$k],"",str_replace($arr[1][$k],"",$v));
            if(in_array($arr[0][$k],$delete_array)){
                unset($arr[0][$k]);
                continue;
            }
            //去除双方律师
            // if()
            // $lawReg="/(".$arr[0][$k].")([\S\s\]){5,40}(律师)/u";
            $lawReg="/(".$arr[0][$k]."[\s\S]{5,15}律师)/u";
            preg_match($lawReg,$str,$nadasdad);
            if($nadasdad){
                unset($arr[0][$k]);
                continue;
            }

        }   
    }

    $arr[0]=array_unique($arr[0]);

    $newArr=[];
    
    foreach($arr[0] as $k=>$v){
        $newArr[$arr[2][$k]][$v]="";
    }

    $newnewArr=[];

    foreach($newArr as $k=>$v){
        $key=0;
        foreach($v as $kk=>$vv){
            $key++;
            if(count($v)==1){
                $newArr[$k][$kk]=$k."某";
            }else{
                $newArr[$k][$kk]=$k."某".$key;
            }   
            $newnewArr[$kk]=$newArr[$k][$kk];
        }
    }

    foreach($newnewArr as $k=>$v){
        $str=str_replace($k,$v,$str);
    }

    return $str;

}

// 

function preg_number($str){ 
    //屏蔽座机
    $str=preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i','$1****$2',$str);
    //屏蔽手机  
    $str=preg_replace('/(1[76358]{1}[0-9])[0-9]{4}( [0-9]{4})/i','$1****$2',$str);
    // //屏蔽银行卡 
    $str=preg_replace('/([0-9]{4}[0-9]{4}[0-9]{4})/i','$1****$2',$str);
    // //屏蔽身份证号
    $str=preg_replace('/([0-9]{18})/i','**********',$str);
    // //屏蔽车牌号
    // $str=preg_replace('/([京|津|沪|渝|冀|豫|云|辽|黑|湘|皖|鲁|新|苏|浙|赣|鄂|桂|甘|晋|蒙|陕|吉|闽|贵|粤|青|藏|川|宁|台|琼|使|领|军|北|南|成|广|沈|济|空|海]){1}([A-Z]){1}([A-Z0-9]){4}([A-Z0-9|挂|领|学|警|港||澳]){1}(?!\d)/i','$1****',$str);
    $str=preg_replace('/([京|津|沪|渝|冀|豫|云|辽|黑|湘|皖|鲁|新|苏|浙|赣|鄂|桂|甘|晋|蒙|陕|吉|闽|贵|粤|青|藏|川|宁|台|琼|使|领|军|北|南|成|广|沈|济|空|海]){1}([A-Z]){1}([A-Z0-9]){4}/i','$1****',$str);
    // //识别代码 
    $str=preg_replace('/([a-zA-Z]{10})/i','***',$str);
    // //不动产权
    $str=preg_replace('/(不动产权)([\S]){1,15}(号)/u','$1****$3',$str);



    return $str;
}




function preg_address($str){
    //屏蔽住址
    $str=preg_replace('/(位于|住){1}([\S]){1,60}([0-9])/i','$1****',$str);
    $str=preg_replace('/(区|市|州|户籍地|区){1}([\S]){5,30}([0-9]|村|房屋|房)/i','$1****',$str);
    //屏蔽工作地址
    $str=preg_replace('/(族[,，]|学院|中国)([\S]){1,60}(职工|教师|官|经理|学生|民|老师|警察)/u','$1****$3',$str);
    // preg_match_all('/(族[,，])([\S]){1,100}(职工|教师|官|经理)/i',$str,$arr);
    $str=preg_replace('/([0-9]){1,2}(月){1}([0-9]){1,2}(日)/i','*$2*$4',$str);

    return $str;
}   


//处理当事人数组
function name_head_sort($arr){
    $newArr=[];
    foreach($arr as $k=>$v){
        // $arr[$k]['newName']=mb_substr($v['name'], 0, 1, 'utf-8')."某".$link;
        $newArr[mb_substr($v['name'], 0, 1, 'utf-8')][]=$v;
    }
    $newArr2=[];
    foreach($newArr as $k=>$v){
        if(count($v)>1){
            foreach($v as $kk=>$vv){
                $newArr2[$vv['name']]=$k."某".($kk+1);
            }        
        }else{
            foreach($v as $kk=>$vv){
                $newArr2[$vv['name']    ]=$k."某";
            }   
        }
    }

    foreach($arr as $k=>$v){

        $arr[$k]['newName']=$newArr2[$v['name']];

    }

    return $arr;
}



//创建 数据库前置选项 data
function data_add($data,$uid){
    $data['created_time']=date("Y-m-d H:i:s",time());
    $data['created_uid']=$uid;

    $userName=DB::table('users')->where('id',$uid)->first()['name'];

    $data['created_username']=$userName;
    $data['update_time']=date("Y-m-d H:i:s",time());
    $data['update_uid']=$uid;
    $data['update_username']=$userName;
    return $data;
}

//修改 数据库前置选项 data
function data_update($data,$uid){
    $data['update_time']=date("Y-m-d H:i:s",time());
    $data['update_uid']=$uid;
    $userName=DB::table('users')->where('id',$uid)->first()['name'];
    $data['update_username']=$userName;

    return $data;
}